package com.linkai.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.linkai.dto.AdminBproductExcelDto;
import com.linkai.service.BproductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author yamon
 * @Date 2020-12-16 17:05
 * @Description
 * @Version 1.0
 */
public class BackProductDataListener extends AnalysisEventListener<AdminBproductExcelDto> {
    private static final Logger log = LoggerFactory.getLogger(BackProductDataListener.class);

    private final List<AdminBproductExcelDto> datas = new ArrayList<>();
    private static final int BATCH_COUNT = 3000;
    public BproductService bproductService;

    public BackProductDataListener(BproductService bproductService) {
        this.bproductService = bproductService;
    }

    public BackProductDataListener() {
    }

    @Override
    public void invoke(AdminBproductExcelDto adminBproductExcelDto, AnalysisContext analysisContext) {
        log.info("进入invoke方法");
        datas.add(adminBproductExcelDto);
        //达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if(datas.size() >= BATCH_COUNT){
            saveData();
            // 存储完成清理datas
            datas.clear();
        }
        System.out.println("******"+adminBproductExcelDto);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    public void saveData(){
        bproductService.batchSaveBackProduct(datas);
    }
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        System.out.println("表头"+headMap);
    }
}
